<template>
  <ul class="list">
    <li class="item" v-for="item of letters" :key="item"
    @click="handleClick"
    @touchstart="handleTouchstart"
    @touchmove="handleTouchmove"
    @touchend="handleTouchend"
    :ref="item"
    >{{item}}</li>
  </ul>
</template>
<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: {
    letters () {
      const letter = []
      for (let i in this.cities) {
        letter.push(i)
      }
      return letter
    }
  },
  data () {
    return {
      isTouchmove: false,
      startY: 0,
      timer: null
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleClick (e) {
      this.$emit('change', e.target.innerHTML)
    },
    handleTouchstart () {
      this.isTouchmove = true
    },
    handleTouchmove (e) {
      if (this.isTouchmove) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          let endY = e.targetTouches[0].clientY - 79
          let index = Math.floor((endY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 10)
      }
    },
    handleTouchend () {
      this.isTouchmove = false
    }
  }
}
</script>
<style lang="scss" scoped>
@import '~styles/variables' ;
.list{
  position: absolute;
  right: 0;
  bottom: 0;
  top: 1.58rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: .4rem;
  .item{
    text-align: center;
    line-height: .4rem;
    color: $baseColor;
  }
}
</style>
